<template>
  <div class="page_message">
    <van-nav-bar title="信息">
      <template #right>
        <van-icon @click="searchType = !searchType" name="search" size="20" style="margin-right: 20px; " />
        <van-icon name="ellipsis" size="18" @click="showOverlay = true" />
      </template>
    </van-nav-bar>

      <van-overlay :show="showOverlay" @click="showOverlay = false" class="over_layer">
        <van-cell-group class="layer">
          <van-cell value="添加好友" @click="add_freind" />
          <van-cell value="好友表" @click="friendList()" />
          <van-cell value="近聘表" @click="platForm()"/>
          <!-- <van-cell value="关闭声音"/> -->
        </van-cell-group>
      </van-overlay>
      <van-search v-if="searchType == true" v-model="value"
          show-action
          placeholder="请输入近聘昵称"
          type='text'
        >
          <template #action>
            <div @click="onSearch">搜索</div>
          </template>
      </van-search>
      <div class="message-box">
      <div class="list" v-if="addUserList.length > 0" v-for="(item, index) in addUserList" :key="index">
        <div class="head_info">
          <div class="head_img">
            <img :src="item.addeduseravatar" style="width:100%;height:100%" alt="" />
          </div>
          <div class="head_fromUser">
            <div class="up">{{ item.addusername }}</div>
            <div class="down">我是{{ item.addusername }}</div>
          </div>
        </div>
        <div class="head_btn">
          <div
            @click="agreeAddUserFired(item, index)"
            style="background:blue;color:#fff;padding:10px;borderRadius:5px;fontWeight:bold;marginRight:10px"
          >
            同意
          </div>
          <div
            @click="refuseFirend(item)"
            style="background:red;color:#fff;padding:10px;borderRadius:5px;fontWeight:bold"
          >
            拒绝
          </div>
        </div>
      </div>
      <div class="message-list">
        <div
          v-show="serviceId == 0"
          class="list-flex"
          @click="chat(item, index)"
          v-for="(item, index) in meassgeList"
          :key="index"
        >
          <div class="flex-icon">
            <span v-if="item.isRead !== 0" class="new-message">{{ item.isRead }}</span>
            <img :src="item.UserImage" style="width:100%;height:100%;border-radius:20px;" />
          </div>
          <div class="flex-message">
            <div class="lt">
              <div class="flex-message-up">
                <div :class="{colorBlue: item.UserId == 'c0395e02-6c0d-4e75-b53e-1ac44904c472'}" class="up-name">
                  {{ item.Name }}
                </div>
                <van-icon v-if="item.GroupId" style="margin-right:5px;margin-top:10px" name="service-o" size="20" />
              </div>
              <div class="flex-message-down" v-if="item.MessageType == 0">{{ item.LastMessage }}</div>
              <div class="flex-message-down" v-if="item.MessageType == 1">【图片】</div>
            </div>
            <div class="rt" v-if="item.UserId == 'c0395e02-6c0d-4e75-b53e-1ac44904c472'">平台客服</div>
            <div class="rt" v-if="item.GroupId == '2'">第三方客服</div>
          </div>
        </div>

        <div
          v-show="serviceId == 1 && item.GroupId"
          class="list-flex"
          @click="chat(item, index)"
          v-for="(item, index) in meassgeList"
          :key="index + '1'"
        >
          <div class="flex-icon">
            <span v-show="item.isRead == 1" class="new-message">{{ isReadCount }}</span>
            <img :src="item.UserImage" style="width:100%;height:100%;border-radius:20px;" />
          </div>
          <div class="flex-message">
            <div class="flex-message-up">
              <div class="up-name">{{ item.Name }}</div>
              <van-icon v-show="item.GroupId" style="margin-right:5px;margin-top:10px" name="service-o" size="20" />
            </div>
            <div class="flex-message-down">{{ item.chatContent }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { createWebscoket, onSend, closeWs } from '@/utils/socket.js'
import {mapState, mapActions} from 'vuex'
import bus from '../../utils/bus.js'
import {Toast} from 'vant'
export default {
  name: 'messages',
  data() {
    return {
      searchType: false,
      addUserList: [],
      isReadCount: 1,
      userId: 2,
      serviceId: 0,
      userType: '客服',
      userInfo: '',
      show: true,
      showOverlay: false,
      meassgeList: [],
      value: '',
      active: 0,
      kefuList: [],
      socketMsg: ''
    }
  },
  computed: {
    chatUserList: function() {
      return this.$store.getters.getChatUserList
    },
    msg: function() {
      console.log(this.isReadCount)
      return this.$store.getters.getMsgFn
    }
  },
  watch: {
    msg: 'newMsgFU'
  },
  created(){
    // this.initWebsocket()
  },
  mounted() {
    console.log(',,,,,,,,,,,,,,,,,')
    let chatUserList = JSON.parse(localStorage.getItem('chatUserList'))

    for (var i = 0; i < chatUserList.length; i++) {
      chatUserList[i].isRead = 0
    }

    console.log(chatUserList)
    console.log('111111111')
    this.meassgeList = chatUserList
    if (this.$route.params.id) {
      //我的客服
      this.serviceId = this.$route.params.id
    }
    this.userInfo = JSON.parse(localStorage.getItem('userInfo')) || ''
    this.getAddUser()
  },


  methods: {
    //连接socket
    initWebsocket() {
      createWebscoket(uri, this.jwt, this.messagesCallBack)
    },
   //新消息监听
   messagesCallBack(msg){
      this.socketMsg = msg
   },

   //发送socket消息到服务器
  sendMessage(){
     onSend(JSON.stringift({
       data: '要发送的消息'
      }))
   },
   //断开socket
   closeWs(){
      closeWs()
   },

    newMsgFU() {
      //更新新消息
      let msgData = JSON.parse(this.msg)
      for (var i = 0; i < this.meassgeList.length; i++) {
        if (msgData.SendUserId == this.meassgeList[i].UserId) {
          this.meassgeList[i].LastMessage = msgData.MessageContent
          if (this.meassgeList[i].isRead == 1) {
            this.meassgeList[i].isRead = 1
            this.meassgeList.unshift(this.meassgeList[i])
            this.meassgeList.splice(i+1,1)
            return
          }else{
            this.meassgeList[i].isRead++
            this.isReadCount++
            return
          }
        }
      }
      console.log(this.meassgeList)
    },
    // 获取添加好友消息
    getAddUser() {
      let params = {
        // userId:'c13f082b-d715-4644-9a84-db51f2f7e697' //  当前用户的id
        userId: this.userInfo.id
      }
      this.$api.user.GetAddFirendList(params).then(res => {
        if (res.code === 200) {
          console.log(res)
          console.log(JSON.parse(res.data))
          this.addUserList = JSON.parse(res.data)
        }
      })
    },
    // 同意添加好友
    agreeAddUserFired(data, index) {
      let params = {
        keyId: data.id
      }
      this.$api.user.AgreeFirend(params).then(res => {
        if (res.code === 200) {
          console.log(res)
          Toast('已添加到好友表')
          this.addUserList.splice(index, 1)
        }
      })
    },
    // RefuseFirend 拒绝添加好友
    refuseFirend(data) {
      let params = {
        keyId: data.id
      }
      this.$api.user.RefuseFirend(params).then(res => {
        if (res.code === 200) {
          console.log(res)
        }
      })
    },
    // 好友列表
    friendList() {
      this.$router.push('addFreidList')
    },
    //客服列表
    customer_service() {
      this.$router.push('customer_service')
    },

    getMsg() {
      var $this = this
      $this.proxy.on('addMessage', data => {
        console.log('接收到服务端的消息')
        let msgData = JSON.parse(data)
        console.log(msgData)
        console.log($this.meassgeList)
        for (let i = 0; i < $this.meassgeList.length; i++) {
          if ($this.meassgeList[i].UserId == msgData.SendUserId) {
            let newChat = $this.meassgeList[i]
            newChat.chatContent = msgData.MessageContent
            //删除之前的位置的数据
            $this.meassgeList.splice(i, 1)
            if (newChat.isRead == 1) {
              newChat.isRead = 1
              $this.isReadCount++
            } else {
              newChat.isRead = 1
            }
            $this.meassgeList.unshift(newChat)
          }
        }
      })
    },
    chat(data, i) {
      console.log(data)
      bus.$emit('sendCount', data.isRead)
      this.signaR.getMessage(data)
      data.isRead = 0
      this.isReadCount = 1
      this.$router.push({name: 'chat', params: data})
    },
    add_freind() {
      this.$router.push({name: 'addFreid'})
    }
  }
}
</script>

<style lang="scss" scoped>
.page_message {
  position: relative;
  min-height: 100vh;
  .over_layer {
    margin-top: 46px;
    height: 100%;
    .layer {
      width: 40%;
      font-size: 14px;
      position: absolute;
      right: 0;
      z-index: 2;
    }
  }
  .message-box {
    width: 100%;
    // height: 100%;
    padding-bottom:50px;
    position: absolute;
    .list {
      padding: 10px;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      .head_info {
        display: flex;
        .head_img {
          width: 40px;
          height: 40px;
          border-radius: 5px;
          margin-right: 10px;
        }
        .head_fromUser {
          margin-right: 10px;
          .up {
            font-size: 16px;
          }
        }
      }
      .head_btn {
        display: flex;
      }
    }
    .message-list {
      width: 100%;
      height: 100%;
      background: #fff;
      .list-flex {
        width: 90%;
        margin: 0 auto;
        overflow: hidden;
        background: #fff;
        height: 50px;
        padding: 5px 0;
        padding-left: 10px;
        padding-right: 1px;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        .flex-icon {
          width: 40px;
          height: 40px;
          margin-top: 2px;
          border-radius: 20px;
          position: relative;
          .new-message {
            overflow: hidden;
            display: inline-block;
            width: 20px;
            height: 20px;
            line-height: 20px;
            text-align: center;
            background: red;
            color: #fff;
            position: absolute;
            right: -5px;
            top: -6px;
            border-radius: 20px;
          }
        }
        .flex-message {
          width: 85%;
          border-bottom: 1px solid #fafafa;
          display: flex;
          flex-direction: row;
          justify-content: space-between;
          align-items: center;
          .lt {
            .flex-message-up {
              font-size: 12px;
              margin-bottom: 5px;
              font-weight: bold;
              display: flex;
              flex-direction: row;
              justify-content: space-between;
              .up-name {
              }
              .up-time {
                margin-right: 10px;
                color: #999;
              }
            }
          }
          .rt {
            width: auto;
            height: 30px;
            font-weight: bold;
            font-size: 16px;
            // border:1px solid #ccc;
            margin-right: 20px;
          }

          .flex-message-down {
            font-size: 12px;
            white-space: nowrap;
            // overflow:hidden;
          }
        }
      }
    }
  }
}
</style>
